#!/usr/bin/env python

############################################################################
#  QLyrics - A simple lyrics viewer.                                       #
#  Copyright (C) 2008  hsys <hanshuiys@gmail.com>                          #
#                                                                          #
#  This program is free software; you can redistribute it and/or modify    #
#  it under the terms of the GNU General Public License as published by    #
#  the Free Software Foundation; either version 3 of the License, or       #
#  (at your option) any later version.                                     #
#                                                                          #
#  This program is distributed in the hope that it will be useful,         #
#  but WITHOUT ANY WARRANTY; without even the implied warranty of          #
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the           #
#  GNU General Public License for more details.                            #
#                                                                          #
#  You should have received a copy of the GNU General Public License       #
#  along with this program; if not, write to the Free Software Foundation, #
#  Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA       #
############################################################################

import os, sys, subprocess, threading, ConfigParser;

# const definition =========================================
QLyricsResponse = {
        "Exit"          : "1",
        "StatusChange"  : "2",
        "TrackChange"   : "3",
        "Configure"     : "4",
        "Title"         : "5",
        "Album"         : "6",
        "Artist"        : "7",
        "Filename"      : "8",
        "Length"        : "9",
        "Time"          : "10"
        }

QLyricsRequest = {
        1 : "Title",
        2 : "Album",
        3 : "Artist",
        4 : "Length",
        5 : "Filename",
        6 : "Time",
        7 : "Exit"
        }

QLyricsStatus = {
        "Playing"       : "1",
        "Paused"        : "2",
        "Idle"          : "3",
        "Closed"        : "4"
        }

# callback definition ======================================
callbacks = {
        }
# ==========================================================

lyricsProcess = None
monitorThread = None

def setEventHandler(name, func):
    global callbacks
    callbacks[name] = func

def eventMonitor():
    global lyricsProcess
    global callbacks
    while True:
        eventId = int(lyricsProcess.stdout.readline())
        if (not (eventId in QLyricsRequest)):
            continue
        event = QLyricsRequest[eventId]
        print >>sys.stderr, "--> Get request: " + event
        if (event in callbacks):
            value = callbacks[event]()
            print >>sys.stderr, "<-- Reply: " + repr(value)
            lyricsProcess.stdin.write(QLyricsResponse[event] + ' ' + value + "\n")
        if (event == "Exit"):
            break;
    lyricsProcess = None

def isRunning():
    global lyricsProcess
    return lyricsProcess != None

def start():
    global lyricsProcess
    global monitorThread
    try:
        config = ConfigParser.ConfigParser()
        config.read(os.environ.get("HOME") + "/.qlyrics/config.ini")
        path = config.get("System", "Path")
        print >>sys.stderr, "--- Find QLyrics path: " + path
    except:
        path = "qlyrics"
    lyricsProcess = subprocess.Popen([path, "--plugin"], stdin = subprocess.PIPE, stdout = subprocess.PIPE)
    monitorThread = threading.Thread(target = eventMonitor)
    monitorThread.start()
    print >>sys.stderr, "--- Start QLyrics"

def stop():
    global lyricsProcess
    lyricsProcess.stdin.write(QLyricsResponse["Exit"] + '\n')
    lyricsProcess = None
    print >>sys.stderr, "--- Stop QLyrics"

def statusChanged(status):
    global lyricsProcess
    if (status in QLyricsStatus):
        print >>sys.stderr, "<-- Send status: " + status
        status = QLyricsStatus[status]
        lyricsProcess.stdin.write(QLyricsResponse["StatusChange"] + ' ' + status + "\n")

def trackChanged():
    global lyricsProcess
    lyricsProcess.stdin.write(QLyricsResponse["TrackChange"] + "\n")
    print >>sys.stderr, "<-- Send track change"

def showConfigureWindow():
    global lyricsProcess
    lyricsProcess.stdin.write(QLyricsResponse["Configure"] + "\n")
    print >>sys.stderr, "<-- Send configure request"

